package com.ruoyi.app.service.impl

import cn.hutool.core.bean.BeanUtil
import cn.hutool.core.collection.CollectionUtil
import cn.hutool.core.collection.ListUtil
import com.baomidou.mybatisplus.extension.kotlin.KtQueryWrapper
import com.baomidou.mybatisplus.extension.plugins.pagination.Page
import com.ruoyi.app.common.*
import com.ruoyi.app.domain.dto.AdvertisingSettingDto
import com.ruoyi.app.domain.vo.*
import com.ruoyi.app.service.IndexApiService
import com.ruoyi.back.domain.*
import com.ruoyi.back.domain.Function
import com.ruoyi.back.domain.v3.CheckStatusEnum
import com.ruoyi.back.domain.v3.MyCollect
import com.ruoyi.back.domain.v3.MyRecord
import com.ruoyi.back.domain.v3.Recommend
import com.ruoyi.back.enums.AdvertisingTypeEnum
import com.ruoyi.back.service.*
import com.ruoyi.back.service.impl.AdvertisingSettingService
import com.ruoyi.back.service.v3.MyCollectService
import com.ruoyi.back.service.v3.MyRecordService
import com.ruoyi.back.service.v3.RecommendService
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Service
import java.io.InputStreamReader
import java.util.regex.Pattern

@Service
class IndexApiServiceImpl : IndexApiService {

    @Autowired
    private lateinit var spreadCenterSettingService: SpreadCenterSettingService

    @Autowired
    private lateinit var wxPaySettingService: WxPaySettingService

    @Autowired
    private lateinit var aliPaySettingService: AliPaySettingService

    @Autowired
    private lateinit var advertisingSettingService: AdvertisingSettingService

    @Autowired
    private lateinit var myRecordService: MyRecordService

    @Autowired
    private lateinit var recommendService: RecommendService

    @Autowired
    private lateinit var myCollectService: MyCollectService


    private val log: Logger = LoggerFactory.getLogger(IndexApiServiceImpl::class.java)
    override fun getBannerList(): Data<List<IndexApiService.WonderfulRecordVo>> {

        val banners = mutableListOf<MyRecord>()

       return Ok("获取首页轮播成功", myRecordService.list(KtQueryWrapper(MyRecord::class.java)
           .eq(MyRecord::top, true))
           .takeIf { it.isNotEmpty() }
           ?.run {
               takeIf { it.size >= 5 }
                   ?.run {
                       map {
                           IndexApiService.WonderfulRecordVo().apply {
                               BeanUtil.copyProperties(it, this)
                               createUsername = it.username
                               likeNum = myCollectService.count(KtQueryWrapper(MyCollect::class.java)
                                   .eq(MyCollect::recordId, it.id)
                                   .eq(MyCollect::mode, 1)).toLong()
                               like = myCollectService.like(it.id!!)
                               collect = myCollectService.collect(it.id!!)
                               id = it.id!!.toInt()
                           }
                       }.take(5)
                   }
                   ?: run {
                       banners.addAll(this)
                       myRecordService.list(KtQueryWrapper(MyRecord::class.java)
                           .eq(MyRecord::recommendBanner, true)
                           .eq(MyRecord::top, false))
                           .takeIf { it.isNotEmpty() }
                           ?.run {
                               banners.addAll(toSet().shuffled().take(5 - banners.size))
                           }
                       banners.map {
                           IndexApiService.WonderfulRecordVo().apply {
                               BeanUtil.copyProperties(it, this)
                               createUsername = it.username
                               likeNum = myCollectService.count(KtQueryWrapper(MyCollect::class.java)
                                   .eq(MyCollect::recordId, it.id)
                                   .eq(MyCollect::mode, 1)).toLong()
                               like = myCollectService.like(it.id!!)
                               collect = myCollectService.collect(it.id!!)
                               id = it.id!!.toInt()
                           }
                       }
                   }
           }
           ?: run {
               myRecordService.list(KtQueryWrapper(MyRecord::class.java)
                   .eq(MyRecord::recommendBanner, true))
                   .takeIf { it.isNotEmpty() }
                   ?.run {
                       this.shuffle()
                       take(5).map {
                           IndexApiService.WonderfulRecordVo().apply {
                               BeanUtil.copyProperties(it, this)
                               createUsername = it.username
                               likeNum = myCollectService.count(KtQueryWrapper(MyCollect::class.java)
                                   .eq(MyCollect::recordId, it.id)
                                   .eq(MyCollect::mode, 1)).toLong()
                               like = myCollectService.like(it.id!!)
                               collect = myCollectService.collect(it.id!!)
                               id = it.id!!.toInt()
                           }
                       }
                   }

           }
       )

    }

    override fun wonderfulRecord(pageNum: Long?, pageSize: Long?): Data<PageData<IndexApiService.WonderfulRecordVo>> =
        myRecordService.page(
            Page(pageNum!!, pageSize!!), KtQueryWrapper(MyRecord::class.java)
                .eq(MyRecord::shelves, true)
                .orderByDesc(MyRecord::shelvesTime)
        )
            .let { page ->
                Ok("获取首页作品成功", Page<IndexApiService.WonderfulRecordVo>()
                    .apply {
                        BeanUtil.copyProperties(page, this)
                        records = page.records.takeIf { it.isNotEmpty() }
                            ?.run {
                                map {
                                    IndexApiService.WonderfulRecordVo().apply {
                                        BeanUtil.copyProperties(it, this)
                                        createUsername = it.username
                                        like = myCollectService.like(it.id!!)
                                        likeNum = myCollectService.count(KtQueryWrapper(MyCollect::class.java)
                                            .eq(MyCollect::recordId, it.id)
                                            .eq(MyCollect::mode, 1)).toLong()
                                        collect = myCollectService.collect(it.id!!)
                                        id = it.id!!.toInt()
                                    }
                                }
                            }
                    }.pageInfo()
                )
            }


    override fun getGlobalSetting(): Data<GlobalSetting> =
        Ok("获取全局配置参数成功", GlobalSetting().apply {
            spreadCenterSettingService.getOne(
                KtQueryWrapper(SpreadCenterSetting::class.java)
                    .eq(SpreadCenterSetting::channelType, 1)
            )?.let {
                BeanUtil.copyProperties(it, this)
            }

            wxPaySettingService.getOne(KtQueryWrapper(WxPaySetting::class.java))
                ?.let {
                    wxPayIcon = it.isUse ?: false
                }

            aliPaySettingService.getOne(KtQueryWrapper(AliPaySetting::class.java))
                ?.let {
                    aliPayIcon = it.isUse ?: false
                }
        })

    override fun getIosGlobalSetting(): Data<GlobalSetting> =
        Ok("获取全局配置参数成功", GlobalSetting().apply {
            spreadCenterSettingService.getOne(
                KtQueryWrapper(SpreadCenterSetting::class.java)
                    .eq(SpreadCenterSetting::channelType, 2)
            )?.let {
                BeanUtil.copyProperties(it, this)
            }

            wxPaySettingService.getOne(KtQueryWrapper(WxPaySetting::class.java))
                ?.let {
                    wxPayIcon = it.isUse ?: false
                }

            aliPaySettingService.getOne(KtQueryWrapper(AliPaySetting::class.java))
                ?.let {
                    aliPayIcon = it.isUse ?: false
                }
        })

    override fun getAdvertisingSetting(advertisingSettingDto: AdvertisingSettingDto): Data<AdvertisingSettingVo> =
        Ok("获取广告配置参数成功", advertisingSettingService.getOne(KtQueryWrapper(AdvertisingSetting::class.java)
            .eq(AdvertisingSetting::advertisingType, advertisingSettingDto.advertisingType))
            ?.let {
                AdvertisingSettingVo().apply {
                    BeanUtil.copyProperties(it, this)
                }
            } ?: AdvertisingSettingVo())
    override fun resolveVideo(urlText: String): Data<List<VideoVo>> =
        urlText.urls().takeIf { it.isNotEmpty() }
            ?.run {
                Ok("提取短视频成功", mapNotNull {
                    it.spider()
                })
            } ?: Fail("暂时没有提取出来相关链接!")


    fun String.api() = "https://tenapi.cn/video/?url=$this"
    fun String.urls(): List<String> =
        Pattern.compile("(https?|ftp|file)://[-A-Za-z0-9+&@#/%?=~_|!:,.;]+[-A-Za-z0-9+&@#/%=~_|]")
            .let { pattern ->
                val urls = arrayListOf<String>()
                pattern.matcher(this).let { matcher ->
                    while (matcher.find()) {
                        urls.add(matcher.group())
                    }
                }
                urls
            }
}


